package com.yonyou.iuap.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.JPEGEncodeParam;
import com.yonyou.iuap.base.utils.BaseToolsUtils;
import com.yonyou.iuap.base.vo.FastDfsMsgVO;
import com.yonyou.iuap.pub.IDFactory;
import com.yonyou.iuap.pub.JsonUtils;
import com.yonyou.iuap.shell.entity.exp.ShellFileUpPoJo;
import com.yonyou.iuap.shell.pub.FileTypeUtils;
import com.yonyou.iuap.shell.pub.ResultDto;
import com.yonyou.iuap.shell.service.intf.IFtpService;
import com.yonyou.iuap.shell.service.intf.IKmFileManagerService;
import com.yonyou.iuap.shell.util.ShellUtils;


@Controller
@RequestMapping("/file")
public class KmFtpFileContronller {
	private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
	@Autowired
	private IKmFileManagerService iKmFileManagerService;
	@Autowired
	private IFtpService ftpService;
	@RequestMapping("/uploadFile")
	@ResponseBody
	public Object uploadFile(@RequestBody String picHref,HttpServletRequest request,HttpServletResponse response){
		return ftpUpload(request);
//		return localUpload(request);
	}

	private Object localUpload(HttpServletRequest request){
		ResultDto rsDto = new ResultDto();
		ShellFileUpPoJo filepojo = new ShellFileUpPoJo();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        InputStream is= null;
        int width = 0; // 原始图片宽
        int height = 0; // 原始图片高
        try {
            is = multipartFile.getInputStream();
            BufferedImage bufimg = ImageIO.read(is);
            // 只有图片才获取高宽
            if (bufimg != null) {
                width = bufimg.getWidth();
                height = bufimg.getHeight();
                filepojo.setWidth(String.valueOf(width));
                filepojo.setHeight(String.valueOf(height));
            }
            String originalFilename = multipartFile.getOriginalFilename(); // 文件全名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length()); // 后缀
            filepojo.setFile_name(originalFilename.substring(0,originalFilename.lastIndexOf(".")));
//            ftp实例
            FTPClient ftpClient = new FTPClient();
            ftpService.login(ftpClient);
            
          //将。tiff格式图片转为jpg
            boolean istiff=false;
            if("tiff".equals(suffix)||"TIFF".equals(suffix)){
            	suffix="jpg";
            	istiff=true;
            }
            filepojo.setFile_hz(suffix);
            filepojo.setFile_size(multipartFile.getSize());
            String filecode=IDFactory.getInstance().getID()+"."+filepojo.getFile_hz();
            
            String path1 = BaseToolsUtils.getPropertiesValue("encrypt_ftp_path")+filecode;
            File localFile = new File(path1);
            
            if(istiff){
            	//转存到临时文件
            	File temp=new File(BaseToolsUtils.getPropertiesValue("encrypt_ftp_path")+"temp"+IDFactory.getInstance().getID()+".tiff");
//            	本地文件存储
//            	multipartFile.transferTo(temp);
            	
//            	ftp上传
            	ftpService.uploadFile(ftpClient, "", "temp"+IDFactory.getInstance().getID()+".tiff", multipartFile.getInputStream());
            	
            	FileSeekableStream stream = new FileSeekableStream(temp); 
            	RenderedOp src = JAI.create("stream", stream);
            	OutputStream os = new FileOutputStream(path1);
    			JPEGEncodeParam param = new JPEGEncodeParam();
    	        //指定格式类型，jpg 属于 JPEG 类型  
    	        ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param);  
    	        enc.encode(src);
    	        os.flush();
    	        os.close();
    	        stream.close();
    	        FileUtils.forceDelete(temp);  
            }else{
//            	本地文件存储
//            	multipartFile.transferTo(localFile);
//            	ftp上传
            	ftpService.uploadFile(ftpClient, "", filecode, multipartFile.getInputStream());
            }
            
            filepojo.setFile_path(path1);
           
            filepojo.setFileurl("http://"+BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip")+BaseToolsUtils.getPropertiesValue("encrypt_htttp_hz")+filecode);
            
            FastDfsMsgVO msgvo = null;
            msgvo =iKmFileManagerService.uploadFileForFtp(filepojo);
            
            if(FileTypeUtils.getFileType(suffix)==0){
            	Base64 encoder = new Base64();
            	msgvo.setPic_string(encoder.encodeToString(IOUtils.toByteArray(multipartFile.getInputStream())));
            }
            msgvo.setFile_name(filepojo.getFile_name());
//            msgvo.setFile_url("http://"+BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip")+"/"+filename);
            msgvo.setFile_url("http://"+BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip")+BaseToolsUtils.getPropertiesValue("encrypt_htttp_hz")+filecode);
            msgvo.setFile_size(ShellUtils.getFileSize(multipartFile.getSize()));
            msgvo.setFile_hz(suffix);
            rsDto.setStatus(msgvo.getStatus());
    		rsDto.setMessage(msgvo.getMsg());
    		
    		rsDto.setData(msgvo);
            
        } catch (Exception e) {
            e.printStackTrace();
            rsDto.setStatus(-1);
            rsDto.setMessage(e.getMessage());
        }
		
		return rsDto;
	}

	private Object ftpUpload(HttpServletRequest request) {
		logger.info("文件上传接口开始"+String.valueOf(System.currentTimeMillis()));
		ResultDto rsDto = new ResultDto();
		ShellFileUpPoJo filepojo = new ShellFileUpPoJo();
//		新建临时文件夹
		final String tempdir=request.getRealPath("")+"\\temp\\"+ShellUtils.getRemoteHost(request);
		 File file = new File(tempdir);
		 if(!file.exists()||!file.isDirectory()){
			 file.mkdirs();
		 }
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        final MultipartFile multipartFile = multipartRequest.getFile("file");
        InputStream is= null;
        int width = 0; // 原始图片宽
        int height = 0; // 原始图片高
        try {
            is = multipartFile.getInputStream();
            BufferedImage bufimg = ImageIO.read(is);
            // 只有图片才获取高宽
            if (bufimg != null) {
                width = bufimg.getWidth();
                height = bufimg.getHeight();
                filepojo.setWidth(String.valueOf(width));
                filepojo.setHeight(String.valueOf(height));
            }
            String originalFilename = multipartFile.getOriginalFilename(); // 文件全名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length()); // 后缀
            filepojo.setFile_name(originalFilename.substring(0,originalFilename.lastIndexOf(".")));
            
          //将。tiff格式图片转为jpg
            boolean istiff=false;
            if("tiff".equals(suffix)||"TIFF".equals(suffix)){
            	suffix="jpg";
            	istiff=true;
            }
            filepojo.setFile_hz(suffix);
            filepojo.setFile_size(multipartFile.getSize());
            String filecode=IDFactory.getInstance().getID()+"."+filepojo.getFile_hz();
            final File localFile = new File(tempdir+"\\"+filecode);

            if(istiff){
            	try {
    	        	//转存到临时文件
    	        	File temp=new File(tempdir+"\\temp"+IDFactory.getInstance().getID()+".tiff");
    	        	multipartFile.transferTo(temp);
    	        	
    	        	FileSeekableStream stream = new FileSeekableStream(temp); 
    	        	RenderedOp src = JAI.create("stream", stream);
    	        	OutputStream os = new FileOutputStream(localFile);
    	        	JPEGEncodeParam param = new JPEGEncodeParam();
    	        	//指定格式类型，jpg 属于 JPEG 类型  
    	        	ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param);  
    	        	enc.encode(src);
    	        	os.flush();
    	        	os.close();
					stream.close();
					FileUtils.forceDelete(temp); 
				} catch (Exception e) {
					e.printStackTrace();
				}
            	 
            }else{
//            	本地文件存储
            	try {
					multipartFile.transferTo(localFile);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
				}
            }
            
            filepojo.setFile_path(BaseToolsUtils.getPropertiesValue("encrypt_ftp_path")+filecode);
           
            filepojo.setFileurl("http://"+BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip")+BaseToolsUtils.getPropertiesValue("encrypt_htttp_hz")+filecode);
            
            FastDfsMsgVO msgvo = null;
            msgvo =iKmFileManagerService.uploadFileForFtp(filepojo);
            
            if(FileTypeUtils.getFileType(suffix)==0){
            	Base64 encoder = new Base64();
            	msgvo.setPic_string(encoder.encodeToString(IOUtils.toByteArray(multipartFile.getInputStream())));
            }
            msgvo.setFile_name(filepojo.getFile_name());
            msgvo.setFile_url("http://"+BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip")+BaseToolsUtils.getPropertiesValue("encrypt_htttp_hz")+filecode);
            msgvo.setFile_size(ShellUtils.getFileSize(multipartFile.getSize()));
            msgvo.setFile_hz(suffix);
            rsDto.setStatus(msgvo.getStatus());
    		rsDto.setMessage(msgvo.getMsg());
    		rsDto.setData(msgvo);
            
        } catch (Exception e) {
            e.printStackTrace();
            rsDto.setStatus(-1);
            rsDto.setMessage(e.getMessage());
        }
        logger.info("文件上传接口结束"+String.valueOf(System.currentTimeMillis()));
		return rsDto;
	}
	
	
	@RequestMapping("/uploadicon")
	@ResponseBody
	public String uploadicon(HttpServletRequest request,HttpSession session){
		ResultDto rsDto = new ResultDto();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("Filedata");
        String originalFilename = multipartFile.getOriginalFilename(); // 文件全名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length()); // 后缀
        String icon_name=IDFactory.getInstance().getID()+suffix;
        session.setAttribute("icon_name", icon_name);
        
        File temp=new File("D://apache-tomcat-7.0.56//webapps//shellkm//images//"+icon_name);
    	try {
			multipartFile.transferTo(temp);
			
		} catch (Exception e) {
			e.printStackTrace();
			rsDto.setStatus(1);
			rsDto.setMessage("头像上传失败");
			return JsonUtils.toJsonStr(rsDto);
		}
		rsDto.setStatus(0);
		rsDto.setMessage("头像上传成功");
		return JsonUtils.toJsonStr(rsDto);
	}
	
	@RequestMapping("/delFile")
	@ResponseBody
	public String deleteFile(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		logger.info("文件删除接口开始"+String.valueOf(System.currentTimeMillis()));
		ResultDto rsDto = new ResultDto();
//		本地删除
//		FastDfsMsgVO msgvo = iKmFileManagerService.deleteFileForTom(map);
//		ftp删除
		FastDfsMsgVO msgvo = iKmFileManagerService.deleteFileForFtp(map);
		rsDto.setStatus(msgvo.getStatus());
		rsDto.setMessage(msgvo.getMsg());
		logger.info("文件删除接口结束"+String.valueOf(System.currentTimeMillis()));
		return JsonUtils.toJsonStr(rsDto);
	}
//	pc端文件下载
	@RequestMapping("/downloadFile/{id}")
	@ResponseBody
	public String  downloadFile(@PathVariable String id,HttpServletRequest request,HttpServletResponse response){
		logger.info("pc端文件下载接口开始"+String.valueOf(System.currentTimeMillis()));
		ResultDto rsDto = new ResultDto();
		Map<String, String> map=new HashMap<String, String>();
		map.put("pk_att", id);
		System.out.println("附件pk: "+id);
		 FastDfsMsgVO msgvo = iKmFileManagerService.downFileForFtp(map);
		 if(msgvo.getStatus()!=0){
			 rsDto.setStatus(-1);
			 rsDto.setMessage("未获取到需要下载的文件!");
		 }else{
			 
			 OutputStream out = null;
//	         ftp实例
	         FTPClient ftpClient = new FTPClient();
			 try {
				 ftpService.login(ftpClient);
				 ftpClient.enterLocalPassiveMode();
				String filename = new String((StringUtils.isEmpty(msgvo.getFile_name())?"unknown":msgvo.getFile_name()).getBytes("GBK"),"ISO-8859-1");
				String filekz = (StringUtils.isEmpty(msgvo.getFile_hz())?"":msgvo.getFile_hz());
				String pathName=msgvo.getFile_url().substring(msgvo.getFile_url().lastIndexOf("/")+1);
	        	response.reset();
	        	response.setContentLength(Integer.parseInt(msgvo.getFile_size()));
	    		response.setContentType(FileTypeUtils.contentType(msgvo.getFile_type())+";charset=utf-8");
	            response.addHeader("Content-Disposition", "attachment;fileName=" + filename);
				out = response.getOutputStream();
				boolean success=ftpClient.retrieveFile(new String(pathName.getBytes("GBK"),"ISO-8859-1"), out);
			} catch ( Exception e) {
				e.printStackTrace();
				rsDto.setStatus(-1);
				rsDto.setMessage("【下载失败：】"+e.getMessage());
			}finally{
				if(out!=null){
					try {
						out.close();
						ftpService.logout(ftpClient);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} 
		 }
		 logger.info("pc端文件下载接口结束"+String.valueOf(System.currentTimeMillis()));
         return JsonUtils.toJsonStr(rsDto);
	}
//	app端文件下载
	@RequestMapping("/appdownloadFile/{id}")
	public void  appdownloadFile(@PathVariable String id,HttpServletRequest request,HttpServletResponse response){
		logger.info("app端文件下载接口开始"+String.valueOf(System.currentTimeMillis()));
		Map<String, String> map=new HashMap<String, String>();
		 map.put("pk_att", id);
		 FastDfsMsgVO msgvo = iKmFileManagerService.downFileForFtp(map);
		 
//	     ftp实例
        FTPClient ftpClient = new FTPClient();
        OutputStream out = null;
		 try {
			 ftpService.login(ftpClient);
			 ftpClient.enterLocalPassiveMode();
			 String filename = new String((StringUtils.isEmpty(msgvo.getFile_name())?"unknown":msgvo.getFile_name()).getBytes("GBK"),"UTF-8");
//		   String filekz = (StringUtils.isEmpty(msgvo.getFile_hz())?"":msgvo.getFile_hz());
		   String pathName=msgvo.getFile_url().substring(msgvo.getFile_url().lastIndexOf("/")+1);
	       response.reset();
		   out = response.getOutputStream();
		   boolean result=ftpClient.retrieveFile(new String(pathName.getBytes("GBK"),"ISO-8859-1"), out);
		   if(result){
			   response.setContentLength(Integer.parseInt(msgvo.getFile_size()));
			   response.setContentType(FileTypeUtils.contentType(msgvo.getFile_type())+";charset=utf-8");
			   response.addHeader("Content-Disposition", "attachment;fileName=" + filename);
		   }else{
			   response.setStatus(500);
		   }
		} catch ( Exception e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
					ftpService.logout(ftpClient);
					logger.info("app文件下载接口结束"+String.valueOf(System.currentTimeMillis()));
				} catch (Exception e) {
					e.printStackTrace();
					response.setStatus(500);
				}
			}
		} 
	}
//	图片预览
	@RequestMapping("/picdownload/{id}")
	@ResponseBody
	public String  picdownload(@PathVariable String id,HttpServletRequest request,HttpServletResponse response){
		logger.info("图片预览接口开始"+String.valueOf(System.currentTimeMillis()));
		 Map<String, String> map=new HashMap<String, String>();
		 map.put("pk_att", id);
		 FastDfsMsgVO msgvo = iKmFileManagerService.downFileForFtp(map);
		 ByteArrayOutputStream out =null;
		 byte[] byteout=null;
		 String outstr ="";
//	     ftp实例
         FTPClient ftpClient = new FTPClient();
		 try {
			ftpService.login(ftpClient);
			ftpClient.enterLocalPassiveMode();
			String pathName=msgvo.getFile_url().substring(msgvo.getFile_url().lastIndexOf("/")+1);
			out = new ByteArrayOutputStream();
			boolean success = ftpClient.retrieveFile(new String(pathName.getBytes("GBK"),"ISO-8859-1"), out);
			if(success){
				byteout=out.toByteArray();
				Base64 encoder = new Base64(); 
				outstr = encoder.encodeToString(byteout);
			}else{
				response.setStatus(404);
			}
		} catch ( Exception e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
					ftpService.logout(ftpClient);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} 
		 logger.info("图片预览接口结束"+String.valueOf(System.currentTimeMillis()));
         return outstr;
	}
}
